#!/bin/sh

. jobs/job.subr

NODES=1
CORES=12

next_nr()
{
	name="${1}"

	nr=`find "${RESULTS}" -type f -name "${name}.[0-9]*.yoda" -printf "%f\n" | sed -En 's/'${name}'.([0-9]*).yoda/\1/p' | sort -n | tail -n 1`
	if [ -n "${nr}" ]; then
		nr=`expr ${nr} + 1`
	else
		nr=0
	fi

	touch ${RESULTS}/${name}.${nr}.yoda
	echo ${nr}
}

generate_job()
{
	name="${1}"
	events="${2}"
	nr=`next_nr ${name}`

	cat << EOF > ${JOBS}/${name}.${nr}.job
#!/bin/sh

. ${PROJECT}/jobs/job.subr

run ${name} ${nr} ${events}
EOF
	chmod +x ${JOBS}/${name}.${nr}.job

	echo ${nr}
}

run_job()
{
	queue="${1}"
	name="${2}"
	nr="${3}"

	qsub -d ${WORKDIR} -q ${queue} -l nodes=${NODES}:ppn=${CORES} -N ${name}.${nr} -m ea ${JOBS}/${name}.${nr}.job
}

queue="${1}"
name="${2}"
events="${3}"
nr="${4}"
if [ -z "${queue}" ] || [ -z "${name}" ] || [ -z "${events}" ] || [ -z "${nr}" ]; then
	echo "${0} queue dat-name events number"
	exit 1
fi

for i in `seq 1 ${nr}`; do
	run_job "${queue}" "${name}" `generate_job "${name}" "${events}"`
done
